package top.someapp.dxf2dsvg.jfx;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author zwz
 * Created on 2020-04-23
 */
class ResourceBundleControl extends ResourceBundle.Control {
    private static final List<String> formats = Arrays.asList("xml", "properties");

    @Override
    public List<String> getFormats(String baseName) {
        return formats;
    }

    @Override
    public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
            throws IllegalAccessException, InstantiationException, IOException {
        if ("xml".equals(format)) {
            String bundleName = toBundleName(baseName, locale);
            String resourceName = toResourceName(bundleName, format);
            return new XmlResourceBundle(loader.getResourceAsStream(resourceName));
        }
        return super.newBundle(baseName, locale, format, loader, reload);
    }

    class XmlResourceBundle extends ResourceBundle {
        private final Properties props;

        XmlResourceBundle(InputStream stream) throws IOException {
            props = new Properties();
            props.loadFromXML(stream);
        }


        @Override
        protected Object handleGetObject(String key) {
            return props.getProperty(key);
        }

        @Override
        public Enumeration<String> getKeys() {
            Set<String> handleKeys = props.stringPropertyNames();
            return Collections.enumeration(handleKeys);
        }
    }
}
